﻿using System;
using System.Linq;
using System.Web.Mvc;
using Actya.Core;
using Actya.Core.Infrastructure;
using Actya.Core.SiteStructure;
using Actya.Web.Mvc.Helpers;
using Actya.Web.ViewModels.Admin;

namespace Actya.Web.Controllers.CmsAdmin
{
	[Authorize(Roles = RoleNames.CmsAdministrators)]
    public class SiteController : Controller
    {
		private ISiteService _siteService;
    	private ICmsContext _cmsContext;
		private readonly ICmsHost _cmsHost;

    	public SiteController(ISiteService siteService, ICmsContext cmsContext, ICmsHost cmsHost)
    	{
    		_siteService = siteService;
    		_cmsContext = cmsContext;
    		_cmsHost = cmsHost;
    	}

    	public ActionResult Index()
		{
			var editSiteViewModel = new EditSiteViewModel();
    		editSiteViewModel.AvailableThemes = _cmsContext.Site.Themes.Select(t => t.Name).ToArray();
    		editSiteViewModel.Name = _cmsContext.Site.Name;
    		editSiteViewModel.DefaultTheme = _cmsContext.Site.DefaultTheme;
			return View(editSiteViewModel);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult UpdateSite(EditSiteViewModel viewModel)
		{
			if (ModelState.IsValid)
			{
				var site = _cmsContext.Site;
				site.Name = viewModel.Name;
				site.DefaultTheme = viewModel.DefaultTheme;
				try
				{
					this._siteService.UpdateSite(site);
					this.ShowMessage(MessageType.Success, string.Format("Site properties are changed successfully."), true);
					return RedirectToAction("Index");
				}
				catch (Exception ex)
				{
					this.ShowMessage(MessageType.Error, ex.Message);
				}
			}
			viewModel.AvailableThemes = _cmsHost.GetAvailableThemes().Select(t => t.Name).ToArray();
			return View(viewModel);
		}
    }
}
